//
//  AppsFlyerCocosSDK.swift
//  Game105Client-mobile
//
//  Created by Developer001 on 2025/3/31.
//

import Foundation
import AppsFlyerLib
import AppTrackingTransparency

@objc class AppsFlyerCocosSDK : UIResponder, SDKDelegate, @preconcurrency AppsFlyerLibDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: AppsFlyerCocosSDK?
    
    var viewController :UIViewController?
    
    let devKey = "euAYgsBifJq5rDeqPoL2Pj"
    let appleAppId = "6745811539"
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@AppLovinCocosSDK launched")
        
        AppsFlyerCocosSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        
        JsbSDK.onMsg("AppsFlyerCocosSDK.logEvent", handler: self.logEvent)
        
        
        AppsFlyerLib.shared().appsFlyerDevKey = devKey
        AppsFlyerLib.shared().appleAppID = appleAppId
        AppsFlyerLib.shared().customerUserID = ThinkingCocosSDK.instance?.distinctId // 产生关联
        
        print("AppsFlyerCocosSDK: customerUserID \(AppsFlyerLib.shared().customerUserID ?? "n/a")")
        
        AppsFlyerLib.shared().isDebug = false
        AppsFlyerLib.shared().delegate = self
        
        
        NotificationCenter.default.addObserver(self, selector: NSSelectorFromString("sendLaunch"), name: UIApplication.didBecomeActiveNotification, object: nil)
                
        return true
    }
    
    // SceneDelegate support
    @objc func sendLaunch() {
        AppsFlyerLib.shared().waitForATTUserAuthorization(timeoutInterval: 60)
        AppsFlyerLib.shared().start()
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { (status) in
                switch status {
                case .denied:
                    print("AuthorizationSatus is denied")
                case .notDetermined:
                    print("AuthorizationSatus is notDetermined")
                case .restricted:
                    print("AuthorizationSatus is restricted")
                case .authorized:
                    print("AuthorizationSatus is authorized")
                @unknown default:
                    fatalError("Invalid authorization status")
                }
           }
        }
    }
    
    //    @objc func applicationDidBecomeActive(_ application: UIApplication) {
    //        AppsFlyerLib.shared().start()
    //    }
    
    func logEvent(args:String?) {
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let eventName = json["eventName"] as? String
                    print("@logEvent", eventName as Any)
                    AppsFlyerLib.shared().logEvent(eventName!, withValues: [:])
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func onConversionDataSuccess(_ conversionInfo: [AnyHashable : Any]) {
        print("@onConversionDataSuccess", conversionInfo);
        JsbSDK.sendMsg("AppsFlyerSDKManager.responseConversionData", args: conversionInfo)
    }
    
    func onConversionDataFail(_ error: any Error) {
        print("@onConversionDataFail", error);
    }
    
    func onAppOpenAttribution(_ attributionData: [AnyHashable : Any]) {
        print("@onAppOpenAttribution", attributionData);
    }
    
    func onAppOpenAttributionFailure(_ error: any Error) {
        print("@onAppOpenAttributionFailure", error);
    }

}
